var exec = require("child_process").exec;
var querystring = require("querystring");
var fs = require("fs");

function sleep(milliSeconds) {
    var start = new Date().getTime();
    while(new Date().getTime() < start + milliSeconds);
}

function start(response, request, postData) {

    //todo the logic for /
    console.log("request handler for start is been called");
    var body = '<html>' +
                '<head>' +
                    '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' +
                    '<title>Start</title>' +
                '</head>' +
                '<body>' +
                    '<form action="/upload" method="post">' +
                        '<textarea name="text" rows="20" cols="60"></textarea>' +
                        '<input type="submit" value="Submit text">' +
                    '</form>' + 
                '</body>' +
                '</html>';

    response.writeHeader(200, {"Content-Type" : "text/html"});
    response.write(body);
    response.end();
}

function upload(response, request, postData) {
    //todo the logic for /upload
    console.log("request handler for upload is been called");
    response.writeHeader(200, {"Content-Type" : "text/plain"});
    response.write("You've sent " + querystring.parse(postData).text);
    response.end();
}

//TODO the showJSON
function showTopo(response,request,postData) {
    console.log("request handler for showTopo is been called");
    var topoData;

    fs.readFile("./data/topoOutput.json", 'utf8', function(err,data){
        if(err) {
            console.log("err in open topoOutput.json");
        }
        else {
            topoData = data;
            console.log(data);
            response.writeHeader(200,{"Content-Type" : "application/json"});
            response.write(data);
            response.end();
        }
    });
}

/*
function topologyPage(response) {
    console.log("request for the topology page");
    fs.readFile("./page/topology.html", 'utf8',function(err,data) {
        response.writeHeader(200,{"Content-Type" : "text/html"});
        response.write(data);
        response.end();
    });
}
*/
exports.start = start;
exports.upload = upload;
exports.showTopo = showTopo;
//exports.topology = topologyPage;